package com.example.lean;

import android.content.pm.ActivityInfo;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity implements SensorEventListener {     //实现传感器监听接口
    SensorManager sm;   //用来引用传感器管理员
    Sensor sr;         //用来引用加速传感器对象
    TextView txv;      //用来引用画面中的文字组件
    ImageView igv;     //用来引用画面中要移动的小图
    RelativeLayout layout;     //用来引用画面中的Layout组件
    double mx = 0, my = 0;          //用来存储x,y方向每一等分的大小

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);     //设置屏幕不随手机旋转
        sm = (SensorManager) getSystemService(SENSOR_SERVICE);        //从系统服务获取传感器管理员
        sr = sm.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);       //获取加速传感器
        txv = findViewById(R.id.txvIno);        //获取TextView组件
        igv = findViewById(R.id.igvMove);        //获取要移动的Imageview组件
        layout = findViewById(R.id.layout);       //获取layout组件
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        //获取小图的LayoutParm对象
        RelativeLayout.LayoutParams parms = (RelativeLayout.LayoutParams) igv.getLayoutParams();
        int posx = (int) ((10 - event.values[0]) / 10 * (layout.getWidth() - igv.getWidth()) / 2);
        int posy = (int) ((10 + event.values[1]) / 10 * (layout.getHeight() - igv.getHeight()) / 2);
        //处理边界条件只能在0和屏幕范围之间
        posx = posx < 0 ? 0 : posx;
        posx = posx > (layout.getWidth() - igv.getWidth()) ? (layout.getWidth() - igv.getWidth()) : posx;
        posy = posy < 0 ? 0 : posy;
        posy = posy > (layout.getHeight() - igv.getHeight()) ? (layout.getHeight() - igv.getHeight()) : posy;
        //设置左,上边界
        parms.leftMargin = posx;
        parms.topMargin = posy;
        igv.setLayoutParams(parms); //将小图应用LayoutParm，使边界设置生效
        //加速度改变时
        String msg = String.format("X轴:%1.2f\nY轴:%1.2f\nZ轴:%1.2f\n屏幕宽高:%d,%d\n图片左上角位置:%d,%d",
                event.values[0], event.values[1], event.values[2], layout.getWidth(), layout.getHeight(), posx, posy);
        txv.setText(msg);
    }


    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
    }

    @Override
    protected void onResume() {
        super.onResume();
        sm.registerListener(this, sr, SensorManager.SENSOR_DELAY_NORMAL);   //向加速传感器（sr）注册监听对象（this）
    }

    @Override
    protected void onPause() {
        super.onPause();
        sm.unregisterListener(this);    //取消监听对象（this）的注册
    }
}